package com.zwcl.payment.gateway.controller.callback;

import com.zwcl.payment.gateway.constants.PayConstants;
import com.zwcl.payment.gateway.mq.producer.MqProducer;
import com.zwcl.payment.gateway.utils.WXPayUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Map;

/**
 * 微信回调接口（普通商户）
 * Created by kunye on 2019/8/1
 */
@Controller
@Slf4j
public class WeixinNormalCallbackController {

    @Autowired
    private MqProducer mqProducer;

    private static final String SUCCESS = "<xml><return_code><![CDATA[SUCCESS]]></return_code></xml>";

    private static final String FAIL = "<xml><return_code><![CDATA[FAIL]]></return_code></xml>";

    /**
     * 微信小程序支付回调
     */
    @RequestMapping(value = PayConstants.WEIXIN_MINA_NORMAL_PAY_CALLBACK_URL, method = RequestMethod.POST)
    public void weixinJsapiPayCallback(HttpServletRequest request, HttpServletResponse response) throws Exception {
        try {
            Map<String, String> params = WXPayUtil.xmlStreamToMap(new InputStreamReader(request.getInputStream()));
            boolean isSuccess = mqProducer.wxNormalPayCallBack(params);
            if(!isSuccess){
                response.getWriter().write(FAIL);
                return;
            }
            response.getWriter().write(SUCCESS);
        } catch (Exception e) {
            log.error("微信小程序支付回调异常", e);
            response.getWriter().write(FAIL);
        }
    }

    /**
     * 微信小程序退款回调
     */
    @RequestMapping(value = PayConstants.WEIXIN_MINA_NORMAL_REFUND_CALLBACK_URL, method = RequestMethod.POST)
    public void weixinJsapiRefundCallback(HttpServletRequest request, HttpServletResponse response) throws IOException {
        try {
            Map<String, String> params = WXPayUtil.xmlStreamToMap(new InputStreamReader(request.getInputStream()));
            boolean isSuccess = mqProducer.wxNormalRefundCallBack(params);
            if(!isSuccess){
                response.getWriter().write(FAIL);
                return;
            }
            response.getWriter().write(SUCCESS);
        } catch (Exception e) {
            log.error("微信退款回调异常", e);
            response.getWriter().write(FAIL);
        }
    }
}
